package com.congee02.graph;

import java.util.*;
import java.util.function.*;

public class GraphDFS_Recursive {

    public void dfs(int num, int[][] edges, Consumer<Integer> consumer) {

        List<Integer>[] graph = new List[num];

        for (int[] edge : edges) {

            int from = edge[0];
            int to = edge[1];

            if (graph[from] == null) {
                graph[from] = new ArrayList<>();
            }

            graph[from].add(to);

        }

        boolean[] visited = new boolean[num];
        for (int i = 0 ; i < num ; i ++ ) {
            if (! visited[i]) {
                doDfs(graph, visited, i, consumer);
            }
        }

    }

    private void doDfs(List<Integer>[] graph, boolean[] visited, int cur, Consumer<Integer> consumer) {
        visited[cur] = true;

        consumer.accept(cur);

        if (graph[cur] == null) {
            return;
        }

        for (Integer neighbor : graph[cur]) {
            doDfs(graph, visited, neighbor, consumer);
        }

    }

}
